package com.jeeplus.invoice.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class MiniProgramTools {
	
	/**
	 * 获取微信access_token
	 * @param appid   小程序appid
	 * @param secret  小程序秘钥
	 * @return
	 */
	public static String getAccessToken(String appid,String secret){
		//微信公众平台认证接口地址
		String url = "https://api.weixin.qq.com/cgi-bin/token";
		//认证参数构建
		Map<String,String> param = new HashMap<String,String>();
		param.put("grant_type", "client_credential");
		param.put("appid", appid);
		param.put("secret", secret);
		//返回认证结果
		String wxResult = HttpClientUtil.doGet(url,param);
		//格式化处理
		Map<String,Object> model = JsonUtil.jsonToMap(wxResult);
		//获取OpenID对象
		Object objAccessToken = model.get("access_token");
		//从OpenID对象得到OpenID字符串，获取失败返回失败结果
		return objAccessToken == null ? "" : objAccessToken.toString();
	}
	
	/**
     * 生成带参小程序二维码
     * @param access_token  认证方式
     * @param paraMap       参数集合
     * @return
     */
    public static byte[] getMiniQR(String access_token, Map<String, Object> paraMap) throws Exception {
        byte[] result ;
        String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        // 设置请求的参数
        JSONObject postData = new JSONObject();
        for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
            postData.put(entry.getKey(), entry.getValue());
        }
        httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toByteArray(entity);
        return result;
    }
    
    /**
     * 生成带参小程序二维码
	 * @param appid   小程序appid
	 * @param secret  小程序秘钥
     * @param paraMap 参数集合
     * @return
     */
    public static byte[] getMiniQR(String appid,String secret, Map<String, Object> paraMap) {
    	String access_token = MiniProgramTools.getAccessToken(appid, secret);
    	System.out.println("access_token="+access_token);
    	try {
			return MiniProgramTools.getMiniQR(access_token, paraMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null ;
    }
}
